﻿#region
using System;
using System.Linq;
using System.Text.RegularExpressions;
using Google.GData.Client;
using Google.GData.YouTube;
using Google.YouTube;
using YoutubeExtractor;

#endregion

namespace Y2M2
{
    public class YoutubeHelper
    {
        private const string key = "AI39si4QWBbUZTl_SCt_lPg_mAWrPmmyHGf_HBz3B00Ke0eGMFnz_s-rD5OMGSRMDskV3YDEvVaPK4zyzPQZd0Q3S_saB531_g";

        public static Clip GetClipInfoFromUrl(string url)
        {
            string videoId = GetVideoId(url);

            if (videoId == null)
                return null;

            YouTubeRequestSettings settings = new YouTubeRequestSettings("Castpia", key);
            YouTubeRequest request = new YouTubeRequest(settings);

            string entryUrl = "http://gdata.youtube.com/feeds/api/videos/" + videoId;
            Video video = request.Retrieve<Video>(new Uri(entryUrl));

            if (video == null)
                return null;

            return GetClipInfoFromClip(new Clip(video));
        }

        private static string GetVideoId(string url)
        {
            Match match = Regex.Match(url, @"youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase);

            return match.Success ? match.Groups[1].Value : null;
        }

        private static Clip GetClipInfoFromClip(Clip clip)
        {
            var clipInfoList = (from x in DownloadUrlResolver.GetDownloadUrls(clip.WatchPage.ToString())
                                where x.VideoType == VideoType.Mp4 || x.VideoType == VideoType.Flash
                                select new ClipInfo(x, clip)).ToList();
            clipInfoList.Sort(new ClipInfoComparer());

            return clipInfoList.Count > 0 ? clipInfoList[0].Clip : null;
        }
    }
}